package com.edu.whty.common.tools;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

public class FileUtil {
	
	private FileUtil(){
		
	}
	
	/**
	 * 单态实例
	 */
	private static FileUtil instance;
	
	
	/**
	 * 获得单态实例
	 * 
	 * @return 单态实例
	 */
	public static FileUtil getInstance() {
		if (instance == null) {
			instance = new FileUtil();
		}
		return instance;
	}
	
	private static List<String> fileTypes = new ArrayList<String>();
	static {
		fileTypes.add("image");
		fileTypes.add("video");
		fileTypes.add("music");
		fileTypes.add("doc");
		fileTypes.add("xls");
		fileTypes.add("ppt");
		fileTypes.add("txt");
		fileTypes.add("pdf");
	}
	
	/**
	 * @author 黄凯
	 * @param file
	 * @return file md5值
	 */
	 public static String getMD5(File file) {
		  String MD5 = "";
		  try {
			  if(file!=null){
		      FileInputStream fos = new FileInputStream(file);
		      java.security.MessageDigest alga = java.security.MessageDigest.getInstance("MD5");
		      //设置填充大小
		      byte[] buffer = new byte[1024];
		      //实际读取的字节数
		      int read;
		      while ((read = fos.read(buffer, 0, 1024)) > 0) {
		    	  alga.update(buffer, 0, read);
		      }
		      byte[] digesta = alga.digest();
		      for (int i = 0; i < digesta.length; i++) {
		    	  MD5 += Integer.toHexString((0x000000ff & digesta[i]) | 0xffffff00).substring(6);
		      }
		      }
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
		  return MD5;
	 }
	 
		/**
		 * 获取文件大小
		 * @param f
		 * @return
		 * @throws Exception
		 */
		public static Integer getFileSizes(File f) throws Exception {// 取得文件大小
			Integer s = 0;
			if (f.exists()) {
				FileInputStream fis = null;
				fis = new FileInputStream(f);
				s = fis.available();
			} else {
				f.createNewFile();
			}
			return s;
		}
		
		/**
		 * 获取文件后缀名
		 * @param filePath
		 * @return
		 */
		public static String getFileType(String filePath){
			int dot=filePath.lastIndexOf(".");
			if(dot > -1){
				return filePath.substring(dot+1);
			}else {
				return "";
			}
		}
		
		/**
		 * 删除单个文件
		 * 
		 * @param fileName
		 *            被删除文件的文件名
		 * @return 单个文件删除成功返回true,否则返回false
		 */
		public static  boolean delFile(String fileName) {
			File file = new File(fileName);
			if (file.isFile() && file.exists()) {
				file.delete();
				//System.out.println("删除单个文件" + fileName + "成功！");
				return true;
			} else {
				//System.out.println("删除单个文件" + fileName + "失败！");
				return false;
			}
		}
		
		/**
		  * 返回文件类型
		  * 文件类型有以下几种：
		  * doc,html(智能组卷使用),image,movie,music,pdf,ppt,txt,xls
		  * @param path
		  * @return
		  */
		 public String getFileTypeByPath(String path) {
			 for(String key : fileTypes) {
				 String imageTypesStr = SysConfig.getStrValue(key);
				 String[] suffixNames = imageTypesStr.split(",");
				 String pathSuffix = path.substring(path.lastIndexOf('.')+1);
				 for(String suffixName : suffixNames) {
					 if(suffixName.equals(pathSuffix)) {
						 return key;
					 }
				 }
			 }
			 return "html";
		 }
		 
			/**
			 * 取得指定目录下的所有文件列表，包括子目录.
			 * 
			 * @param baseDir
			 *            File 指定的目录
			 * @return 包含java.io.File的List
			 */
			public static List getSubFiles(File baseDir) {
				List ret = new ArrayList();
				File[] tmp = baseDir.listFiles();
				for (int i = 0; i < tmp.length; i++) {
					if (tmp[i].isFile()) {
						ret.add(tmp[i]);
					}
					if (tmp[i].isDirectory()) {
						ret.addAll(getSubFiles(tmp[i]));
					}
				}
				return ret;
			}
		/**
		 * 判断操作系统是不是windows
		 * 
		 * @return boolean
		 */
		public static boolean isWindows() {
			boolean flag=false;
			String os = System.getProperty("os.name");  
			if(os.toLowerCase().startsWith("win")){  
				flag=true;
			} 
			return flag;
		}
		
		/**
		 * @category 创建目录
		 * @param path
		 * @return
		 */
		public static boolean checkMkdirs(String path){
			File folder = new File(path);
			if(!folder .exists()  && !folder .isDirectory()){
				folder.mkdirs();
				return true;
			}
			else
				return false;
			
		}

	public static String getCosKey(String fileName,String userId,String platformCode) {
		Calendar now = Calendar.getInstance();
		String year = String.valueOf(now.get(Calendar.YEAR));
		String month = String.valueOf(now.get(Calendar.MONTH) + 1);
		String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
		String hour = String.valueOf(now.get(Calendar.HOUR_OF_DAY));
		String min = String.valueOf(now.get(Calendar.MINUTE));
		StringBuilder relativeDirPath = new StringBuilder();
		//relativeDirPath.append(SysConf.gfsRootDir).append("/").append(SysConf.gfsCurVol);
		if(StringUtils.isNotBlank(platformCode)) {
			relativeDirPath.append("/").append(platformCode);
		}
		relativeDirPath.append("/").append(year);
		relativeDirPath.append("/").append(month);
		relativeDirPath.append("/").append(day);
		relativeDirPath.append("/").append(hour);
		relativeDirPath.append("/").append(min);
		relativeDirPath.append("/").append(userId);
		relativeDirPath.append("/").append(UUID.randomUUID().toString().replaceAll("-",""));
		relativeDirPath.append("/").append(fileName);
		return relativeDirPath.toString();
	}
}
